/**
 * 文本溢出后自动显示...，只有显示...后才启动 Tooltip 的纯文本组件
 * 用法很简单，类似 <span /> 标签
 */

import React, { useState, useRef, useEffect } from "react";
import { Tooltip } from "antd";
import clsx from "clsx";
import { TooltipPlacement } from "antd/es/tooltip";

interface ProTextTruncateProps {
  placement?: TooltipPlacement;
  className: string; // 请通过 className 来设置最大宽度，如 w-40, w-2/4，如果在 flex 下面，自动撑满，设置为 flex-grow，外层不能加flex否则无法换行判断是否超长
  children: React.ReactNode;
  onClick?: () => void;
  lines?: number;
}

export default function ProTextTruncate(props: ProTextTruncateProps) {
  const { className, children, placement = "bottomLeft", lines = 1 } = props;
  const textRef = useRef<HTMLDivElement>(null);
  const [isOverflowing, setIsOverflowing] = useState(false);

  useEffect(() => {
    function checkOverflow() {
      const current = textRef.current;
      if (current) {
        // 检查是否溢出：scrollWidth > clientWidth 或 scrollHeight > clientHeight
        const isOverflow =
          current.scrollWidth > current.clientWidth ||
          current.scrollHeight > current.clientHeight;
        setIsOverflowing(isOverflow);
      }
    }

    // 使用 setTimeout 确保 DOM 已经渲染完成
    const timer = setTimeout(checkOverflow, 0);
    window.addEventListener("resize", checkOverflow);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", checkOverflow);
    };
  }, [children]);

  return (
    <Tooltip
      overlayClassName="text-xs" // 应用自定义样式类
      title={isOverflowing ? children : ""}
      placement={placement}
    >
      <div
        ref={textRef}
        className={clsx("typography-multiline-ellipsis", className)}
        style={{ "--line-clamp": lines } as React.CSSProperties}
        onClick={props.onClick}
      >
        {children}
      </div>
    </Tooltip>
  );
}
